import moment from 'moment';
import _ from 'lodash';
import { TRAlert } from '#/components';

// 表格基础样式
export const tableStyle = {
  // '--header-bgcolor': '#434749',
  // '--header-color': 'white',
  '--border-color': 'rgba(255, 255, 255, 0.1)',
  '--header-row-height': '36px',
  /* // '--header-row-height': '28px',
  // '--row-height': '28px', */
  '--font-size': '12px',
  // '--cell-border-vertical': '1px solid rgba(255, 255, 255, 0.1)',
  // '--header-cell-border-vertical': '1px solid rgba(255, 255, 255, 0.1)',
  // '--bgcolor': '#222629',
  // '--color': 'white',
  // '--hover-bgcolor': '#222629',
  '--cell-padding': '4px 5px',
  // border: '1px solid #444',
  borderRadius: '5px',
};

export const initTime = () => {
  return Array.from({ length: 96 }, (_, i) => {
    let num = (i + 1) * 15;
    num = Math.floor(num / 60) * 100 + (num % 60);
    num = ('' + num).padStart(4, '0');
    return {
      value: i + 1,
      label: num,
    };
  });
};

// 根据value获取时间点
export const getTimePointByValue = (value = 1) => {
  let num = (value + 1) * 15;
  num = Math.floor(num / 60) * 100 + (num % 60);
  num = ('' + num).padStart(4, '0');
  return num;
};

export const getTimeSlot = () => {
  return Array.from({ length: 12 }, (_, i) => {
    let num =
      (String(i * 2) + '15').padStart(4, '0') +
      '-' +
      ((i < 11 ? String(i * 2 + 2) : '00') + '00').padStart(4, '0');
    return {
      value: num,
      label: num,
      points: [i * 8 + 1, (i + 1) * 8],
    };
  });
};
export const getTimesPoint = (time = moment().format('HH::ss')) => {
  if (time) {
    const t = time.toString();
    let hour = t.slice(0, 2);
    let min = t.slice(-2);
    const data = Number(hour) * 4 + Math.floor((min - 1) / 15) + 1;
    return data;
  }
};

// 分解xxxx-xxxx时点为两个时刻点
export const resolveTime = (str = '0015-0030') => {
  return str.split('-');
};

// 根据planData构建stationObj
export const buildStationObjByData = (planData = []) => {
  const obj = {};
  planData?.forEach((i, k) => {
    i?.strategyList?.map((v) => {
      if (v.markDate) {
        const markDateArr = v.markDate.split(',');
        markDateArr.map((d) => {
          let arr = obj[d] || [];
          let stationIds = v?.stationIds?.map((i) => ({
            value: i,
            username: planData[k]['title'],
          }));
          stationIds = stationIds || [];
          arr = [...arr, ...stationIds];
          obj[d] = arr;
        });
      }
    });
  });
  return obj;
};

// 获取被操作的场站数组
export const getHandleStationIds = (value = [], oldValue = []) => {
  let deleteValue = _.cloneDeep(oldValue);
  let commonValue = [];
  let addValue = [];
  value.forEach((i, k) => {
    if (oldValue.indexOf(i) !== -1) {
      commonValue.push(i);
      deleteValue = deleteValue.filter((v) => v !== i);
    } else {
      addValue.push(i);
    }
  });
  return {
    commonValue,
    addValue,
    deleteValue,
  };
};

// 判断同一个标的日下是否有相同场站
export const isSelectStation = (stations = [], value = [], oldValue = []) => {
  const arr = [];
  stations?.forEach((i) => {
    if (value.includes(i.value)) {
      arr.push(i.value);
    }
  });
  if (arr.length === 0) {
    return false;
  } else {
    TRAlert.error('存在重复交易单元!');
    return true;
  }
};

// 禁用日趋
export const disabledDate = (current, endOrder) => {
  const endTime = Number(endOrder);
  let currentDate = moment().format('HH:mm').replace(':', '');
  currentDate = Number(currentDate);
  if (currentDate >= endTime) {
    return current && current < moment().endOf('days').add(1, 'days');
  } else {
    return current && current < moment().endOf('days');
  }
};

// 返回step为1的数组
export const mergeStep = (data = []) => {
  return data.filter((i) => i.step === 1);
};

// 构建需要的planData
export const buildPlanData = (data = [], type) => {
  const arr = _.cloneDeep(data);
  arr.forEach((i) => {
    const buildTableLine = (arr) => {
      arr?.forEach((d) => {
        d.timePeriod = d.startOrder + '-' + d.endOrder;
        if (d.electricType === 1) {
          d.electric1 = Math.round(d.electric * 100);
        } else {
          d.electric2 = d.electric;
        }
        if (d.children instanceof Array) {
          d.disabled = true;
        }
        buildTableLine(d?.children || []);
      });
    };
    i?.strategyList?.forEach((v) => {
      if (v.hourOrderList instanceof Array) {
        v.hourOrderList = v.hourOrderList.map((h) => {
          let value = TimeFrameArr.filter((f) => f.label === h);
          value = value?.[0]?.['value'] || 1;
          return value;
        });
      }
      v.details = buildDataKey(v.details || []);
      buildTableLine(v.details);
    });
  });
  return arr;
};

// 补全两个日期之间的日期
const fillDates = (date) => {
  if (date) {
    const time = date.split(',');
    const startDate = new Date(time[0]);
    const endDate = new Date(time[1]);
    let dates = [];
    let currentDate = new Date(startDate);
    while (currentDate <= endDate) {
      dates.push(new Date(currentDate));
      currentDate.setDate(currentDate.getDate() + 1);
    }
    return dates.map((i) => moment(i).format('YYYY-MM-DD')).toString();
  }
};

// 构建保存的数据
export const buildSaveData = (value = {}, type, date) => {
  const data = _.cloneDeep(value);
  data?.strategyList?.forEach((s) => {
    s.strategyId = s.strategyId || null;
    s.programmeId = value.programmeId || null;
    // 日内marketDate传连续日期
    if (type === 'intraday') {
      s.markDate = fillDates(date);
    }
    const buildTableLine = (arr) => {
      arr?.forEach((d) => {
        d.electric1 = isNotEmpty(d.electric1) ? Number(d.electric1) : 0;
        d.electric2 = isNotEmpty(d.electric2) ? Number(d.electric2) : 0;
        if (d.electricType === 1) {
          d.electric = d.electric1 / 100;
        } else {
          d.electric = d.electric2;
        }
        d.hourOrderId = d.hourOrderId || null;
        d.strategyId = s.strategyId || null;
        if (d.children) {
          buildTableLine(d.children);
        }
      });
    };
    buildTableLine(s.details);
    // 如果是日内的策略3
    if (s.strategyType === 3 && data.dayTpye === 'intraday') {
      s.details.forEach((d) => {
        const children = [];
        d?.children?.forEach((a) => {
          a?.children?.forEach((b) => {
            children.push({ ...a, ...b });
          });
        });
        d.children = children;
      });
    }
  });
  return data;
};

// 校验保存的数据
export const judgeSave = (value = {}) => {
  let errStatus = false;
  let message = '';
  value?.strategyList?.forEach((v, k) => {
    const stationIds = v.stationIds || [];
    if (stationIds.length === 0) {
      errStatus = true;
      message = `第${k + 1}个策略，请选择交易单元!`;
    }
    // if (!v.markDate) {
    //   errStatus = true;
    //   message = `第${k + 1}个策略，请选择标的日!`;
    // }
  });
  message && TRAlert.error(message);
  return errStatus;
};

// 判断值是否为非空值
export const isNotEmpty = (value) => {
  return value !== undefined && value !== null && value !== '';
};

// 如果为空值则返回红色边框
export const getErrorStyle = (value, style = {}) => {
  return isNotEmpty(value) ? style : { ...style, border: ' 1px solid #eb5757c7' };
};

// 判断界面是否可编辑
export const getEditDisabled = (arr = [], key = '0') => {
  const data = arr ? arr?.[+key] || {} : {};
  if (data.hasOwnProperty('editPermission')) {
    return !data.editPermission;
  } else {
    return false;
  }
};

// 比例值的校验
export const getPercent = (value) => {
  if (value && value > 100) {
    return 100;
  } else if (value && value < 0) {
    return 0;
  } else {
    return value;
  }
};

// 如果传入的值超过三位小数则四舍五入
export const getThreeDecimal = (value) => {
  let v = parseFloat(value);
  if (!isNaN(v)) {
    if (v.toString().split('.')[1] && v.toString().split('.')[1].length > 3) {
      v = v.toFixed(3);
    }
    return v;
  }
};

// 时段数组
export const TimeFrameArr = [
  {
    value: 1,
    label: '00-02',
    order: '0000-0200',
  },
  {
    value: 2,
    label: '02-04',
    order: '0200-0400',
  },
  {
    value: 3,
    label: '04-06',
    order: '0400-0600',
  },
  {
    value: 4,
    label: '06-08',
    order: '0600-0800',
  },
  {
    value: 5,
    label: '08-10',
    order: '0800-1000',
  },
  {
    value: 6,
    label: '10-12',
    order: '1000-1200',
  },
  {
    value: 7,
    label: '12-14',
    order: '1200-1400',
  },
  {
    value: 8,
    label: '14-16',
    order: '1400-1600',
  },
  {
    value: 9,
    label: '16-18',
    order: '1600-1800',
  },
  {
    value: 10,
    label: '18-20',
    order: '1800-2000',
  },
  {
    value: 11,
    label: '20-22',
    order: '2000-2200',
  },
  {
    value: 12,
    label: '22-24',
    order: '2200-2400',
  },
];

// 构建表格数据所需要的key
export const buildDataKey = (v) => {
  let arr = _.cloneDeep(v);
  const build = (a, k = '') => {
    a?.forEach((i, index) => {
      i.key = k + '' ? k + '-' + index : index;
      if (i.children instanceof Array) {
        build(i.children, i.key);
      }
    });
  };
  build(arr);
  return arr;
};

// 将a-b-c转换为[a,b,c]
export const stringToArray = (str) => {
  return str?.split('-')?.map(Number) || [];
};

const getStartEndTime = (v) => {
  let label = TimeFrameArr.filter((b) => b.value === v)?.[0]?.['label'] || '';
  label = label.split('-');
  const s = (label?.[0] || '00') + '00';
  const e = (label?.[1] || '00') + '00';
  return [s, e];
};

// 日内的情况下策略3选中数段添加表格数据的构建方法
export const buildTimeFrameArrTatic3 = (v, strategyData) => {
  let arr = v.map((i) => {
    const [s, e] = getStartEndTime(i);
    let start = getTimesPoint(s);
    let end = getTimesPoint(e);
    start = getTimePointByValue(start);
    end = getTimePointByValue(end - 1);
    return {
      startOrder: s,
      endOrder: e,
      timePeriod: s + '-' + e,
      timeFrameValue: i,
      children: [
        {
          level: 2,
          startOrder: start,
          endOrder: end,
          timePeriod: start + '-' + end,
          children: [
            {
              level: 3,
              step: 1,
              electricType: 1,
              // 当限额条件电力选择为按照最大限额申报时，表格内的电力百分比默认为100%，且不可修改
              electric1: strategyData.electricEnergy === 1 ? 100 : '',
            },
          ],
        },
      ],
      level: 1,
    };
  });
  arr = arr.sort((a, b) => a.timeFrameValue - b.timeFrameValue);
  return arr;
};

// 日内的情况下策略1选中数段添加表格数据的构建方法
export const buildTimeFrameArrTatic1 = (v, strategyData = {}) => {
  let arr = v.map((i) => {
    const [s, e] = getStartEndTime(i);
    let start = getTimesPoint(s);
    let end = getTimesPoint(e);
    start = getTimePointByValue(start);
    end = getTimePointByValue(end - 1);
    return {
      startOrder: start,
      endOrder: end,
      timePeriod: start + '-' + end,
      timeFrameValue: i,
      electricType: 1,
      // 当限额条件电力选择为按照最大限额申报时，表格内的电力百分比默认为100%，且不可修改
      electric1: strategyData.electricEnergy === 1 ? 100 : '',
    };
  });
  arr = arr.sort((a, b) => a.timeFrameValue - b.timeFrameValue);
  return arr;
};

// 日内的情况下策略2选中数段添加表格数据的构建方法
export const buildTimeFrameArrTatic2 = (v, strategyData = {}) => {
  let arr = v.map((i) => {
    const [s, e] = getStartEndTime(i);
    let start = getTimesPoint(s);
    // let end = getTimesPoint(s) + 2;
    let end = getTimesPoint(e);
    start = getTimePointByValue(start);
    end = getTimePointByValue(end - 1);
    return {
      startOrder: s,
      endOrder: e,
      timePeriod: s + '-' + e,
      timeFrameValue: i,
      level: 1,
      children: [
        {
          startOrder: start,
          endOrder: end,
          timePeriod: start + '-' + end,
          electricType: 1,
          // 当限额条件电力选择为按照最大限额申报时，表格内的电力百分比默认为100%，且不可修改
          electric1: strategyData.electricEnergy === 1 ? 100 : '',
          level: 2,
        },
      ],
      disabled: true,
    };
  });
  arr = arr.sort((a, b) => a.timeFrameValue - b.timeFrameValue);
  return arr;
};

export const getHourOrder = (arr = [], v) => {
  let faHourOrder = '';
  if (v.level === 2) {
    let index = v?.key?.split('-')?.[0] || 0;
    index = Number(index);
    faHourOrder = arr?.[index]?.['timePeriod'] || '';
  }
  return faHourOrder;
};

export const getOptionsByHourOrder = (hourOrder) => {
  let options = initTime();
  let startTimeValue = hourOrder.split('-')[0];
  let endTimeValue = hourOrder.split('-')[1];
  const startValue = options.filter((i) => i.label === startTimeValue)?.[0]?.['value'] || 0;
  const endValue = options.filter((i) => i.label === endTimeValue)?.[0]?.['value'] || 96;
  options = options.filter((i) => i.value > startValue && i.value <= endValue);
  return options;
};

export const changePrice = (arr, value) => {
  const newArr = _.cloneDeep(arr || []);
  const fun = (v) => {
    v?.forEach((i) => {
      if (i?.level) {
        if (i.level === 2) {
          i.price = value;
        }
      } else {
        i.price = value;
      }
      fun(i?.children);
    });
  };
  fun(newArr);
  return newArr;
};
